import { createRouter, createWebHashHistory } from "vue-router";
import Layout from "@/layouts/Index.vue";
import { useFoldMenuStore } from "@/store/foldMenu";
import { useSwitchTransitionStore } from "@/store/switchTransition";
import { menusAPI } from "@/api/menus";
const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/redirect",
    component: Layout,
    name: "Redirect",
    children: [
      {
        path: "/redirect/:path(.*)",
        name: "Redirect",
        component: () => import("@/views/redirect/Index.vue"),
        meta: {},
      },
    ],
    meta: {
      hidden: true,
      noTagsView: true,
    },
  },
  {
    path: "/login",
    name: "login",
    meta: { noTagsView: false, title: "登录" },
    component: () => import("@/views/login/Index.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
const asyncRoutesHandler = (routes) =>
  routes.map((route) => {
    // 判断component是否是Layout
    if (route.component === "Layout") {
      route.component = Layout;
    } else {
      // 子路由
      const filePath = route.component;
      route.component = () => import(`../views/${filePath}.vue`);
    }
    // 如果有children 继续递归处理
    if (route.children) {
      route.children = asyncRoutesHandler(route.children);
    }
    return route;
  });

const loadMenus = async (to, next) => {
  const foldMenu = useFoldMenuStore();
  const res = await menusAPI();
  console.log("res", res.data);
  foldMenu.setMenus(res.data);
  // 新路由;
  let routesMenu = [];
  res.data.forEach((item) => {
    routesMenu.push(item);
  });
  const asyncRoutes = asyncRoutesHandler(routesMenu);
  // 404的处理一定要放到最后
  router.addRoute({ path: "/:catchAll(.*)", redirect: { name: "notFound" } });
  // 加入到路由中
  asyncRoutes.forEach((r) => {
    router.addRoute(r);
  });
  // 这次无效的导航 要重新来过
  next({ ...to, replace: true /*不额外向历史记录添加一条访问记录*/ });
};
const whitelist = ["login"];
router.beforeEach((to, from, next) => {
  const foldMenu = useFoldMenuStore();
  const switchTransitionStore = useSwitchTransitionStore();
  const indexFrom = from.meta.index;
  const ToFrom = to.meta.index;
  if (whitelist.includes(to.name)) {
    next();
  }
  if (foldMenu.menus.length === 0) {
    return loadMenus(to, next);
  }
  // 但是在登录之前已经加载过路由
  // 已经有路由菜单,放行到login
  foldMenu.setDefaultActive(to.path);
  if (to.meta.title) {
    document.title = `汇劳动-${to.meta.title}`;
  } else {
    document.title = "汇劳动";
  }
  const direction = indexFrom > ToFrom ? "right" : "left";
  switchTransitionStore.changeDirection(direction);
  next();
});
export default router;
